/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable consistent-return */
/* eslint-disable array-callback-return */
/* eslint-disable @typescript-eslint/no-use-before-define */
/* eslint-disable no-use-before-define */
/* eslint-disable react/no-array-index-key */
import React, { useState, useCallback, useEffect, useMemo, useRef } from 'react';
import PropTypes from 'prop-types';
import { Card, Row, Col, Radio } from 'antd';
import { useInViewport } from 'ahooks';
import { connect, useSelector } from 'dva';
import AddressCascader from '@/components/AddressCascader';
import { Brands, Yzs } from '@/components/Select';
import DataSet from '@antv/data-set';
import { isEqual, isEmpty } from 'lodash';
import { isLegalData, getLStorage } from '@/utils/utils';
import Pies from '../Pies';
import Charts from '../Charts';
import Histogram from '../Histogram';
import styles from './style.less';

const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const legends = {
  in_num: '入库数',
  out_rate: '出库率',
  out_num: '出库数',
  back_num: '退回数',
  sms_num: '短信数',
  complaintRate: '每周投诉率（万分比）',
  inStorageRate: '入库通知率（%）',
  outStorageRate: '3日出库率（%）',
  num: '订单',
  real_num: '实名订单',
  new_add: '新增粉丝',
  total: '累计粉丝',
};
const nameMapToState = {
  yesterdaData: ['yesterdaData'], // 昨日数据总览
  storageSummary: ['canvesList'], // 出入库统计
  brandPie: ['inBrandPieList', 'outBrandPieList', 'orderBrandPieList'], // 品牌占比
  regionalRanking: ['inNumRank', 'outRateRank'], // 区域排名 | 驿站排名
  storageRate: ['inStorageRateList', 'outStorageRateList'], // 入库通知率统计
  complaintRate: ['complaintRateList'], // 投诉率统计
  smsSummary: ['smsSummary'], // 短信统计
  orderSummary: ['orderSummary'], // 订单统计
  fansSummary: ['fansSummary'], // 微信粉丝统计
};
const ds = new DataSet();

const WrapperCharts = props => {
  const {
    title,
    name,
    numType,
    dispatch,
    isZyAccount,
    branchId: initBranchId = [],
    branch: initBranch = [],
    cols,
    chartType,
    transform,
    _length,
    chartTitle,
    showAreaSelect,
    showBrandSelect,
    showYzSelect,
    showDaySelect,
    cmIdFromQuery,
    rankType = [], // 区域排名，驿站排名所需的type参数
    onTabChange,
  } = props;

  const [day, setDay] = useState('7');
  const [brand, setBrand] = useState('all');
  const [cm_id, setCmId] = useState('all');
  const [branchId, setBranchId] = useState(initBranchId);
  const [branch, setBranch] = useState(initBranch);
  const [code, setCode] = useState('');
  const [initCode, setInitCode] = useState('');
  const [reqYzPayload, setYzPayload] = useState({});
  const [chartList, setChartList] = useState({});
  const [inView, setInView] = useState(false);
  const showArr = useMemo(
    () => [showAreaSelect, showBrandSelect, showYzSelect, showDaySelect].filter(i => i),
    [showAreaSelect, showBrandSelect, showYzSelect, showDaySelect],
  );

  const ref = useRef();
  const inViewPort = useInViewport(ref);

  const { key } = useSelector(({ setting }) => setting.options);
  const { phone, inn_area_ids = [], area_ids } = useSelector(
    ({ user }) => user.currentUser.user_info,
  );
  const cacheAreaId = getLStorage(`KB_INN_AREA_${phone}`);
  const isCompany = area_ids == '*';
  // 防止片区被关闭，导致请求带上上一个的片区ID
  const area_id = inn_area_ids.includes(cacheAreaId)
    ? cacheAreaId
    : isCompany
      ? '0'
      : inn_area_ids.join(',');

  useEffect(
    () => {
      inViewPort && setInView(true);
    },
    [inViewPort],
  );

  useEffect(
    () => {
      const reqData = {
        day: 7,
        brand: 'all',
        cm_id: cmIdFromQuery,
        code: initCode,
      };
      setCmId(cmIdFromQuery);
      if (initCode) {
        if (name == 'regionalRanking') {
          reqData.day = 1;
          setDay('1');
        }
        inView && getData(reqData);
      }
    },
    [initCode, getData, name, inView, cmIdFromQuery],
  );

  useEffect(
    () => {
      let _code = '';
      if (!isZyAccount) {
        _code = [...branch].map(i => i.code && i.code).pop();
      } else {
        _code = [...branchId].pop();
      }
      setCode(_code);
    },
    [branch, branchId, isZyAccount],
  );

  useEffect(
    () => {
      // 通过监听来自state里面的列表的长度来更新图表中的数据
      const obj = {};
      nameMapToState[name].forEach((val, index) => {
        if (chartType === 'chart') {
          obj[val] = ds
            .createView()
            .source(isLegalData(props[val], []))
            .transform(transform[index]);
        } else {
          obj[val] = props[val];
        }
      });
      setChartList(obj);
    },
    [_length, chartType, name, transform, props],
  );

  useEffect(
    () => {
      if (isZyAccount) {
        setInitCode([...initBranchId].pop());
        setYzPayload({
          branch_id: [...initBranchId].pop(),
        });
      } else {
        setInitCode([...initBranch].map(i => i.code && i.code).pop());
        setYzPayload({
          code: initCode,
          area_id,
        });
      }
      setBranchId(initBranchId);
      setBranch(initBranch);
    },
    [initBranchId, initBranch, initCode, isZyAccount, area_id],
  );

  const onDayChange = useCallback(
    mode => {
      const selectDay = mode.target.value;
      setDay(selectDay);
      getData({
        day: selectDay,
        cm_id,
        code,
        brand,
      });
    },
    [code, cm_id, brand, getData],
  );

  const onBrandChange = useCallback(
    value => {
      setBrand(value);
      getData({
        day,
        brand: value,
        cm_id,
        code,
      });
    },
    [code, day, cm_id, getData],
  );

  const onAddressSelect = useCallback(
    (value, selectedOptions) => {
      setBranchId(value);
      setCmId('all');
      const payload = {
        day,
        brand,
        cm_id,
      };
      const codeArr = selectedOptions.map(val => {
        for (let i = 0; i < value.length; i += 1) {
          const id = value[i];
          if (id == val.id) {
            return val.code || '';
          }
        }
      });
      const _bracnhId = [...value].pop();
      const _code = [...codeArr].pop();
      const _reqYzPayload = {
        [isZyAccount ? 'branch_id' : 'code']: isZyAccount ? _bracnhId : _code,
      };
      if (isZyAccount) {
        payload.code = _bracnhId;
      } else {
        payload.code = _code;
      }
      if (key === 'yz') {
        _reqYzPayload.area_id = area_id;
      }
      if (isEqual(value, branchId)) return;
      setYzPayload(_reqYzPayload);
      getData(payload);
    },
    [day, cm_id, isZyAccount, branchId, brand, getData, key, area_id],
  );

  const onYzSelect = useCallback(
    options => {
      setCmId(options);
      getData({
        day,
        brand,
        cm_id: options,
        code,
      });
    },
    [code, day, brand, getData],
  );

  const getData = useCallback(
    (payload = {}) => {
      if (key == 'yz') {
        payload.area_id = area_id;
      }

      if (name === 'fansSummary') {
        // storagePic outPic
        delete payload.brand;
        delete payload.cm_id;
        delete payload.branchId;
        delete payload.code;
      }

      if (name !== 'storageSummary') {
        delete payload.brand;
      }

      if (name === 'brandPie' || name === 'outPic') {
        payload.brand = 'all';
      }

      if (name === 'regionalRanking' || name === 'brandPie') {
        rankType.forEach(val => {
          payload.type = val;
          dispatch({
            type: `list/${name}`,
            payload: {
              ...payload,
              pageSize: 10,
            },
          });
        });
        return;
      }

      dispatch({
        type: `list/${name}`,
        payload,
      });
    },
    [name, dispatch, rankType],
  );

  const { yesterdaData = [] } = chartList;

  return (
    <div ref={ref}>
      <Card style={{ minHeight: 400 }}>
        <p style={{ textAlign: 'center', fontSize: '18px', fontWeight: '600' }}>{title}</p>
        <Row>
          {showDaySelect && (
            <Col
              xs={24}
              sm={24}
              md={24}
              lg={24}
              xl={12}
              xxl={24 / showArr.length}
              style={{ marginBottom: '10px' }}
            >
              <Row type="flex" align="middle">
                <Col>
                  <span>选择周期：</span>
                </Col>
                <Col>
                  <RadioGroup onChange={onDayChange} value={day} name={name}>
                    {name === 'regionalRanking' && <RadioButton value="1">昨天</RadioButton>}
                    <RadioButton value="7">最近7天</RadioButton>
                    <RadioButton value="30">最近30天</RadioButton>
                  </RadioGroup>
                </Col>
              </Row>
            </Col>
          )}
          {showBrandSelect && (
            <Col
              xs={24}
              sm={24}
              md={24}
              lg={24}
              xl={12}
              xxl={24 / showArr.length}
              style={{ marginBottom: '10px' }}
            >
              <Row type="flex" align="middle">
                <Col>
                  <span>选择品牌：</span>
                </Col>
                <Col span={18}>
                  <Brands
                    onChange={onBrandChange}
                    value={brand}
                    showSearch
                    placeholder="请选择品牌"
                    style={{ width: '100%' }}
                  />
                </Col>
              </Row>
            </Col>
          )}
          {showAreaSelect &&
            inView && (
              <Col
                xs={24}
                sm={24}
                md={24}
                lg={24}
                xl={12}
                xxl={24 / showArr.length}
                style={{ marginBottom: '10px' }}
              >
                <Row type="flex" align="middle">
                  <Col>
                    <span>选择所属区域：</span>
                  </Col>
                  <Col span={15}>
                    <AddressCascader
                      canChooseParent={!isZyAccount}
                      level={3}
                      width="100%"
                      branch={branch}
                      value={branchId}
                      request
                      changeOnSelect
                      onSelect={onAddressSelect}
                    />
                  </Col>
                </Row>
              </Col>
            )}
          {showYzSelect && (
            <Col
              xs={24}
              sm={24}
              md={24}
              lg={24}
              xl={12}
              xxl={24 / showArr.length}
              style={{ marginBottom: '10px' }}
            >
              <Row type="flex" align="middle">
                <Col>
                  <span>选择驿站：</span>
                </Col>
                <Col span={18}>
                  <Yzs
                    style={{ width: '100%' }}
                    reqPayload={reqYzPayload}
                    repeatRequest
                    value={cm_id}
                    onSelect={onYzSelect}
                  />
                </Col>
              </Row>
            </Col>
          )}
        </Row>
        <Row type="flex">
          {chartType === 'data' ? (
            !isEmpty(yesterdaData[0]) ? (
              <Col span={24}>
                <Row type="flex" justify="space-between">
                  <Col xs={24} sm={24} md={24} lg={24} xl={9} xxl={9}>
                    <Card style={{ textAlign: 'center' }}>
                      <Row>
                        <Col span={24}>
                          <Row type="flex" justify="space-around">
                            <Col span={12}>
                              <Row className={styles.data}>
                                <Col>入库数</Col>
                                <Col>{yesterdaData[0].in_num || '-'}</Col>
                                {isZyAccount && <Col>邮政 {yesterdaData[0].yz_in_num}</Col>}
                                {!isZyAccount && (
                                  <Col>
                                    较前日：
                                    <span
                                      style={{
                                        color: yesterdaData[0].in_growth_num > 0 ? 'green' : 'red',
                                      }}
                                    >
                                      {yesterdaData[0].in_growth_num}
                                    </span>
                                  </Col>
                                )}
                              </Row>
                            </Col>
                            <Col span={12}>
                              <Row className={styles.data}>
                                <Col>出库数</Col>
                                <Col>{yesterdaData[0].out_num || '-'}</Col>
                                {isZyAccount && <Col>邮政 {yesterdaData[0].yz_out_num}</Col>}
                                {!isZyAccount && (
                                  <Col>
                                    较前日：
                                    <span
                                      style={{
                                        color: yesterdaData[0].out_growth_num > 0 ? 'green' : 'red',
                                      }}
                                    >
                                      {yesterdaData[0].out_growth_num}
                                    </span>{' '}
                                  </Col>
                                )}
                              </Row>
                            </Col>
                          </Row>
                        </Col>
                        <Col span={24}>
                          <Row type="flex" justify="space-around">
                            <Col span={12}>
                              <Row className={styles.data}>
                                <Col>退回数</Col>
                                <Col>{yesterdaData[0].back_num || '-'}</Col>
                              </Row>
                            </Col>
                            <Col span={12}>
                              <Row className={styles.data}>
                                <Col>短信数</Col>
                                <Col>{yesterdaData[0].sms_num || '-'}</Col>
                              </Row>
                            </Col>
                          </Row>
                        </Col>
                      </Row>
                    </Card>
                  </Col>
                  <Col xs={24} sm={24} md={24} lg={24} xl={4} xxl={5}>
                    <Card style={{ textAlign: 'center' }}>
                      <Row>
                        <Col>
                          <Row className={styles.data}>
                            <Col>寄件订单数</Col>
                            <Col>{yesterdaData[0].order_num || '-'}</Col>
                          </Row>
                        </Col>
                        <Col>
                          <Row className={styles.data}>
                            <Col>快递费</Col>
                            <Col>{yesterdaData[0].fee_num || '-'}</Col>
                          </Row>
                        </Col>
                      </Row>
                    </Card>
                  </Col>
                  <Col xs={24} sm={24} md={24} lg={24} xl={9} xxl={9}>
                    <Card style={{ textAlign: 'center' }}>
                      <Row>
                        <Col span={24}>
                          <Row type="flex" justify="space-around">
                            <Col span={12}>
                              <Row className={styles.data}>
                                <Col>新增站点数</Col>
                                <Col>{yesterdaData[0].station_num || '-'}</Col>
                                <Col>累计 {yesterdaData[0].total_station_num}</Col>
                              </Row>
                            </Col>
                            <Col span={12}>
                              <Row className={styles.data}>
                                <Col>三日出库率</Col>
                                <Col>{yesterdaData[0].out_rate || '-'}%</Col>
                              </Row>
                            </Col>
                          </Row>
                        </Col>
                        <Col span={24}>
                          <Row type="flex" justify="space-around">
                            <Col span={12}>
                              <Row className={styles.data}>
                                <Col>新增粉丝数</Col>
                                <Col>{yesterdaData[0].fans_num || '-'}</Col>
                                <Col>累计 {yesterdaData[0].total_fans_num}</Col>
                              </Row>
                            </Col>
                            <Col span={12}>
                              <Row className={styles.data}>
                                <Col>投诉率（万分比）</Col>
                                <Col>{yesterdaData[0].complaint_rate || '-'}</Col>
                              </Row>
                            </Col>
                          </Row>
                        </Col>
                      </Row>
                    </Card>
                  </Col>
                </Row>
              </Col>
            ) : (
              <div style={{ textAlign: 'center', width: '100%' }}>暂无数据</div>
            )
          ) : (
            nameMapToState[name].map((val, index, arr) => {
              if (chartList[val]) {
                switch (chartType) {
                  case 'chart':
                    return (
                      <Col
                        xs={24}
                        sm={24}
                        md={24}
                        lg={24}
                        xl={24}
                        xxl={24 / arr.length}
                        key={index}
                      >
                        <Charts
                          loading={props.loading}
                          cols={cols}
                          canvesList={chartList[val]}
                          legends={legends}
                          title={chartTitle[index]}
                        />
                      </Col>
                    );
                  case 'pies':
                    return (
                      <Col
                        xs={24}
                        sm={24}
                        md={24}
                        lg={24}
                        xl={24}
                        xxl={24 / arr.length}
                        key={index}
                      >
                        <Pies
                          piesList={chartList[val]}
                          numType={numType}
                          loading={props.loading}
                          title={chartTitle[index]}
                        />
                      </Col>
                    );
                  case 'histogram':
                    return (
                      <Col
                        xs={24}
                        sm={24}
                        md={24}
                        lg={24}
                        xl={12}
                        xxl={24 / arr.length}
                        key={index}
                      >
                        <Histogram
                          redirect={onTabChange}
                          rankType={val}
                          loading={props.loading}
                          list={chartList[val]}
                          title={chartTitle[index]}
                        />
                      </Col>
                    );
                  default:
                    break;
                }
              }
              return null;
            })
          )}
        </Row>
      </Card>
    </div>
  );
};

WrapperCharts.propTypes = {
  title: PropTypes.string, // 标题
  // eslint-disable-next-line max-len
  name: PropTypes.string.isRequired, // 该属性与状态管理中的effects名称相对应，storageSummary,brandPie,outPic,smsSummary,orderSummary,complaintRate,storageRate, fansSummary
  chartType: PropTypes.string.isRequired, // 图表类型，chart | pies | data
  isZyAccount: PropTypes.bool.isRequired, // 是否是中邮的账号
  branchId: PropTypes.array.isRequired, // 地区初始的id
  branch: PropTypes.array.isRequired, // 地区初始的下拉options
  cols: PropTypes.object, // 图表的col属性
  transform: PropTypes.array, // 图表数据处理的格式
  numType: PropTypes.string, // pies图表需要的字段
  chartTitle: PropTypes.array, // 图表里面的标题
  showDaySelect: PropTypes.bool,
  showBrandSelect: PropTypes.bool,
  showAreaSelect: PropTypes.bool,
  showYzSelect: PropTypes.bool,
  cmIdFromQuery: PropTypes.string, // 驿站站点管理跳过来所带的驿站id
};

WrapperCharts.defaultProps = {
  title: '',
  cols: {},
  transform: [],
  numType: 'num',
  chartTitle: [],
  showDaySelect: true,
  showBrandSelect: true,
  showAreaSelect: true,
  showYzSelect: true,
  cmIdFromQuery: '',
};

export default connect(({ list, loading }, { name }) => {
  const listName = nameMapToState[name];
  const obj = {};
  // 按需添加对应的redux数据
  for (let i = 0; i < listName.length; i += 1) {
    const element = listName[i];
    obj._length = list[element];
    obj[element] = list[element];
    obj.loading = loading.effects[`list/${name}`];
  }
  return obj;
})(React.memo(WrapperCharts));
